// https://leetcode.cn/problems/find-k-closest-elements/description/

class Solution {
public:
    vector<int> findClosestElements(vector<int>& arr, int k, int x) {
        if (k == arr.size()) return arr;
        
        auto mid = lower_bound(arr.begin(), arr.end(), x);
        int l = mid - arr.begin() - 1;
        int r = l + 1;

        while (k--) {
            if (l < 0) {
                r++;
            } else if (r >= arr.size() || (x - arr[l] <= arr[r] - x)) {
                l--;
            } else {
                r++;
            }
        }

        return vector<int>(arr.begin() + l + 1, arr.begin() + r);
    }
};